const axios = require('axios');
const moment = require('moment');
const { updateGoogleSheet } = require('./updateGoogleSheet');

const getScanType = (scanType) => {
    switch (scanType) {
        case "收件": return { type: "info_received", text: "Picked up"};
        case "到件": return { type: "in_transit", text: "Arrival"};
        case "发件": return { type: "in_transit", text: "Departure"};
        case "留仓": return { type: "in_transit", text: "In station"};
        case "派件": return { type: "out_for_delivery", text: "Out for delivery"};
        case "签收": return { type: "delivered", text: "Delivered"};
        default: return { type: "in_transit", text: "In transit"};
    }
}

const getDate = (date) => {
    const day = date.format("D");
    const dayOfWeek = date.format("ddd");
    const month = date.format("MMM");
    return `${dayOfWeek}, ${day} ${month}`;
}

const getTime = (date) => {
    const hour = date.format("h");
    const minute = date.format("mm");
    const ampm = date.format("A");
    return `${hour}:${minute} ${ampm}`
}

const getLocation = (t) => {
    if(t.scanTypeNameCn === '签收' || t.scanTypeNameCn === '收件') {
        return t.remark.split('【')[0];
    } else {
        return t.acceptAddress;
    }
}

const getContent = t => {
    if(t.scanTypeNameCn === '派件') {
        return `${t.remark}.${t.contactPhone ? `Dispatcher contact: ${t.contactPhone}`: ""}`
    }
        return t.remark;
}

exports.bestTracking = async (tracking, order, route) => {
    try {
        const arr = [];
        const body = JSON.stringify({
            "expressIds": [
                `${tracking}`
            ]
        });
        
        const config = {
            method: 'post',
            // url: 'http://oa.800best.com/best/track',
            url: 'https://oa.800best.icu/best/track',
            headers: { 
                'authorization': 'eyJhbGciOiJIUzI1NiIsIlR5cGUiOiJKd3QiLCJ0eXAiOiJKV1QifQ.eyJzdWIiOiJCZXN0IFVzZXIgSnd0IiwidXNlckluZm8iOiJ7XCJhcHBVc2VySWRcIjpcIjIwMTQyODdcIixcInBob25lXCI6XCIwMzgwNjA4ODEzM1wifSIsImlzcyI6IkVBLUJlc3RBY2NvdW50IiwiZXhwIjoxNjgxNzE5OTE2LCJpYXQiOjE2NzkxMjc2MTZ9.QGUMhV9bWqe68tOJzrAJPj7lrNUdhl2dOcMBD0tvKHQ', 
                'Content-Type': 'application/json', 
                'Cookie': 'SCOUTER=x7vmaa6iu8ssds'
            },
            data : body
        };

        const { data } = await axios.default.request(config);
        const trackingArr = data.data.expressList[0].traceDetails ? data.data.expressList[0].traceDetails.reverse() : [];
        trackingArr.map(t => {
            arr.push({
                content: getContent(t),
                date: getDate(moment(t.acceptTime)),
                time: getTime(moment(t.acceptTime)),
                location: getLocation(t),
                status: getScanType(t.scanTypeNameCn).type
            })
        })
        const finalObj = {
            status: 200,
            latest_status: trackingArr.length === 0 ? "pending" : getScanType(trackingArr[0].scanTypeNameCn).type,
            result: arr,
            info: {courier: "BEST Express", tracking},
        }
        if(finalObj.latest_status === 'delivered') {
            updateGoogleSheet({ ...finalObj, data: order, route }, tracking, true);
        } else {
            updateGoogleSheet({ ...finalObj, data: order, route }, tracking);
        }
    } catch (error) {
        updateGoogleSheet({ data: order, result: 'error', route }, tracking);
    }
}